package com.ay.weixin.fdc.front.usercenter.event.manager;
import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;

import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.intercepter.Before;
import org.lizar.controller.loader.BasicLoader;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.util.MyMath;
import org.lizar.util.StringHelper;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.types.UserType;
import com.ay.weixin.fdc.boss.user.db.FDCAgentDao;
import com.ay.weixin.fdc.boss.user.db.WeiXinInfoDao;
import com.ay.weixin.fdc.boss.user.domain.FDCAgent;
import com.ay.weixin.fdc.boss.user.domain.FDCUserCenter;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;
import com.ay.weixin.fdc.boss.user.domain.UserWeiXinInfo;
import com.ay.weixin.fdc.front.usercenter.event.UserEvent;
import com.ay.weixin.fdc.front.usercenter.event.UserInfoAccess;

public class UserLogin extends Event implements Before{
	private FDCAgentDao user_dao;
	private UserEvent user_event;
	private WeiXinInfoDao weixin_dao;
	private UserInfoAccess user_access;
	private FDCUserCenter user_center;
	@Override
	public void init_property() throws Exception {
		user_dao=Container.get(FDCAgentDao.class);
		user_event=Container.get(UserEvent.class);
		weixin_dao=Container.get(WeiXinInfoDao.class);
		user_access=Container.get(UserInfoAccess.class);
		user_center=Container.get(FDCUserCenter.class);
		
		
	}

	@Override
	public void before(BasicLoader bl) throws ServletException, IOException {
		long wxproject_id=bl.queryPathInt(2);
		bl.setAttr("vcode_used_error_in_times", ProjectConfig.get(wxproject_id,"fdc_usercenter", "vcode_used_error_in_times"));
		bl.setAttr("user_type", UserType.manager.name());
	}
	
	@Override
	public String default_handling_path() {
		return "/fdc/login/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException,
			IOException {
		long project_id=el.queryPathInt(2);
		System.out.println("project_id:"+project_id);
		handle(el,project_id);
	}
	
	public void handle(EventLoader el,long wxproject_id) throws ServletException,
			IOException {
		if(!el.getBool("is_weixin")&&ProjectConfig._bool(wxproject_id,"sys.weixin_only")){
			el.text("invalid visit");
			return;
		}
		if(el.getSessionAttr("user")!=null){
			el.response_to_root("/fdc/usercenter/"+wxproject_id);
			return;
		}
		
		//微信授权
		UserWeiXinInfo weixin_info=el.getSessionAttr("weixin_info",UserWeiXinInfo.class);
		if(weixin_info==null){
			if(StringHelper.equals(el.getAttr("user_type"), "old")){
				user_access.open_id_check(el,Keys.getStr("forward.user_login_old_default_url"),wxproject_id);
			}else{
				user_access.open_id_check(el,Keys.getStr("forward.user_login_default_url"),wxproject_id);
			}
			return;
		}
		
		UserBasic user=null;
		try {
			user=user_dao.getById(weixin_info.getUser_id());
		} catch (SQLException e) {
			e.printStackTrace();
			try_login(el,wxproject_id);
			return;
		}
		
		//用户与weixin账号未关联，让用户去登陆，以便进行关联
		if(user==null){
			try_login(el,wxproject_id);
			return;
		}
		el.setSessionAttr("user",user);
		user_center.setSession(user.getId(), el.getSession());
		el.response_to_root("/fdc/usercenter/"+wxproject_id);
	}
	
	private void try_login(EventLoader el,long wxproject_id) throws IOException, ServletException{
		String phone=el.getStr("phone","").toLowerCase().trim();
		String password=el.getStr("password","").trim();
		String vcode=el.getStr("vcode").trim();
		
		if(StringHelper.isNull(phone)){
			UserEvent.load_vcode_check(el,wxproject_id);
			view(el,wxproject_id);
			return;
		}
		String msg=login(wxproject_id,phone,password, vcode, el);
		
		if(StringHelper.isNotNull(msg)){
			UserEvent.inc_vcode_check(el,wxproject_id);
			el.setAttr("msg", msg);
			el.setAttr("phone", phone);
			el.template("/WEB-INF/template/app/"+wxproject_id+"/fdc/login.vm");
		}else{
			UserEvent.clean_vcode(el);
			UserEvent.setSessionTimeOut(el);
			UserBasic user=el.getSessionAttr("user",UserBasic.class);
			user_center.setSession(user.getId(), el.getSession());
			user_event.update_weixin(el,user.getId());
			el.response_to_root("/fdc/usercenter/"+wxproject_id);
		}
	}
	
	private void view(EventLoader el,long wxproject_id) throws IOException, ServletException{
		el.template("/WEB-INF/template/app/"+wxproject_id+"/fdc/login.vm");
		return;
	}
	
	
	
	private String login(long wxproject_id,String phone,String password,String vcode,EventLoader el) throws IOException{
		boolean need_vcode=el.getSessionAttr("tel_vcode", 0)>=ProjectConfig.getInt(wxproject_id,"fdc_usercenter.vcode_used_error_in_times");
		
		if(need_vcode&&el.getSessionAttr("vcode")!=null&&!StringHelper.equals(vcode.toLowerCase(), el.getSessionAttr("vcode").toString().toLowerCase())){
			return el.i18("login.vcode_invalid");
		}
		
		if(StringHelper.isNull(password)||!StringHelper.isLong(password)||password.length()>Keys.getInt("fdc_usercenter.register_password_max_length")||password.length()<Keys.getInt("fdc_usercenter.register_password_min_length")){
			return String.format(el.i18("fdc_usercenter.password.not.valid"), Keys.getInt("fdc_usercenter.register_password_min_length"),Keys.getInt("fdc_usercenter.register_password_max_length"));
		}
		
		if(StringHelper.isNull(phone)||!StringHelper.isLong(phone)){
			return String.format(el.i18("fdc_usercenter.phone.not.valid"), Keys.getInt("fdc_usercenter.register_phone_length"));
		}
		FDCAgent user=null;
		
		
		try {
			user=user_dao.getByPhone(wxproject_id,phone);
		} catch (SQLException e) {
			e.printStackTrace();
			return el.i18("login.server_error"); 
		}
		if(user==null){
			return el.i18("login.phone_or_password_invalid");
		}
		if(!StringHelper.equals(user.getPassword(), MyMath.encryptionWithMD5(password))){
			return el.i18("login.phone_or_password_invalid");
		}
		el.setSessionAttr("user", user);
		return null;
	}



	

}
